package handler

import (
	"encoding/json"
	"pic-text-hub/cache"
	"pic-text-hub/models"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func TTTT(c *gin.Context) {
	var tent []models.Content
	redis_key := "add"
	cax, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cax == "" {
		models.DB.Model(&models.Content{}).Find(&tent).Order("title desc")
		jsondata, _ := json.Marshal(tent)
		cache.Rdb.Set(cache.Ctx, redis_key, jsondata, time.Minute*2)
	} else {
		json.Unmarshal([]byte(cax), &tent)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": tent,
	})
	return
}
func List(c *gin.Context) {
	var tent []models.Content
	redis_key := "add"
	cax, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cax == "" {
		models.DB.Model(&models.Content{}).Find(&tent).Order("title desc")
		jsondata, _ := json.Marshal(tent)
		cache.Rdb.Set(cache.Ctx, redis_key, jsondata, time.Minute*2)
	} else {
		json.Unmarshal([]byte(cax), &tent)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": tent,
	})
	return
}
func Add(c *gin.Context) {
	title := c.PostForm("title")
	info := c.PostForm("info")
	picture := c.PostForm("picture")
	if title == "" || info == "" || picture == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	data := models.Content{
		Model:   gorm.Model{},
		Title:   title,
		Info:    info,
		Picture: picture,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}
